package com.miaxis.livedetection;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;

import com.miaxis.livedetect.DetectResult;
import com.miaxis.livedetect.LiveDetectActivity;
import com.miaxis.livedetection.test.R;

import timber.log.Timber;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_PERMISSION = 0x01;
    private static final int REQUEST_LIVE_DETECT = 0x10;
    private static final int REQUEST_SHOW_DETECT_RESULT = 0x12;
    private boolean isAllPermissionGranted = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button detectButton = findViewById(R.id.detect);
        detectButton.setOnClickListener(v -> {
            if (isAllPermissionGranted) {
                startLiveDetect();
            } else {
                simpleDialog("请前往设置授予相关权限!");
            }
        });
        processPermission(new String[]{
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA,
                Manifest.permission.READ_PHONE_STATE,
        });
    }

    private void processPermission(String[] permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] temp = new String[permissions.length];
            int position = 0;
            for (String permission : permissions) {
                if (checkSelfPermission(permission) == PackageManager.PERMISSION_DENIED) {
                    temp[position++] = permission;
                }
            }
            if (position != 0) {
                String[] destPermissions = new String[position];
                System.arraycopy(temp, 0, destPermissions, 0, destPermissions.length);
                requestPermissions(destPermissions, REQUEST_PERMISSION);
            } else {
                onAllPermissionGranted();
            }
        } else {
            onAllPermissionGranted();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION) {
            String[] temp = new String[permissions.length];
            int position = 0;
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    temp[position++] = permissions[i];
                }
            }
            if (position == 0) {
                onAllPermissionGranted();
            } else {
                /*String[] destPermissions = new String[position];
                System.arraycopy(temp, 0, destPermissions, 0, destPermissions.length);
                processPermission(destPermissions);*/
                simpleDialog("请前往设置授予相关权限!");
            }
        }
    }


    private void onAllPermissionGranted() {
        isAllPermissionGranted = true;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_LIVE_DETECT) {
            if (resultCode == RESULT_OK) {
                if (null == data) {
                    return;
                }
                Parcelable parcelable = data.getParcelableExtra(LiveDetectActivity.KEY_RESULT);
                Timber.i("result %s ", parcelable);
                if (parcelable instanceof DetectResult) {
                    startResultActivity((DetectResult) parcelable);
                }
            } else {
                Toast.makeText(this, "用户取消了检测", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == REQUEST_SHOW_DETECT_RESULT && resultCode == RESULT_OK) {
            startLiveDetect();
        }
    }

    private void startLiveDetect() {
        Intent intent = new Intent(this, LiveDetectActivity.class);
        intent.putExtra(LiveDetectActivity.KEY_RANDOM, true);
        intent.putExtra(LiveDetectActivity.KEY_PLAY_SOUND, true);
        //intent.putExtra(LiveDetectActivity.KEY_ACTIONS, new int[]{LiveDetectActivity.ACTION_BLINK, LiveDetectActivity.ACTION_NOD, LiveDetectActivity.ACTION_SHAKING});
        startActivityForResult(intent, REQUEST_LIVE_DETECT);
    }

    private void startResultActivity(DetectResult result) {
        Intent intent = new Intent(this, ResultActivity.class);
        intent.putExtra(ResultActivity.KEY_RESULT, result);
        startActivityForResult(intent, REQUEST_SHOW_DETECT_RESULT);
    }

    private void simpleDialog(final String msg) {
        runOnUiThread(() -> new AlertDialog.Builder(MainActivity.this)
                .setTitle("Hint")
                .setMessage(msg)
                .setPositiveButton("OK", null)
                .show());
    }
}
